package service;

import common.Message;
import common.MessageType;
import dao.ChatDao;
import dao.UserDao;
import entity.Chat;
import entity.User;
import tools.ThreadManage;
import view.ServerView;

import java.util.ArrayList;

public class ChatService {

    private ChatDao chatDao = new ChatDao();

    /**
     * 接收聊天消息
     *
     * @param chat
     */
    public void receiveChat(Chat chat) {
        // 将聊天消息保存到数据库
        if (new ChatDao().add(chat)) {
            ServerView.printLog(chat.getSenderQQ() + " 发送消息给 " + chat.getReceiveQQ());
            // 判断用户是否在线
            ServerThread thread = ThreadManage.getThread(chat.getReceiveQQ());
            if (thread != null) {// 用户在线，将信息发送给该用户
                Message message = new Message(MessageType.CHAT_MESSAGE);
                UserDao userDao = new UserDao();
                User sender = userDao.getByQQ(chat.getSenderQQ());
                User recipient = userDao.getByQQ(chat.getReceiveQQ());
                ArrayList<User> users = new ArrayList<>();
                users.add(sender);
                users.add(recipient);
                message.setContent(chat);
                message.setRemark(users);
                thread.send(message);
            }
        }
    }

    /**
     * 获取聊天记录
     *
     * @param qq
     * @param fqq
     */
    public void getChatList(int qq, int fqq) {
        ArrayList<Chat> chatsByQQ = new ChatDao().getChatsByQQ(qq, fqq);
        Message message = new Message(MessageType.GET_CHAT_LIST);
        message.setRemark(String.valueOf(fqq));
        message.setContent(chatsByQQ);
        ServerThread thread = ThreadManage.getThread(qq);
        thread.send(message);
    }
}
